package com.rxsk.cas.filter;

import cn.hutool.json.JSONUtil;
import com.rxsk.cas.component.JwtTokenUtil;
import com.rxsk.cas.exception.JwtTokenException;
import com.rxsk.cas.pojo.UserDetailPlus;
import com.rxsk.cas.properties.CasProperties;
import com.rxsk.cas.response.Response;
import com.rxsk.cas.service.UserDetailsPlusService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Configuration
public class JwtTokenFilter extends OncePerRequestFilter {

    @Resource
    private UserDetailsPlusService userDetailsPlusService;

    @Resource
    private CasProperties casProperties;

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {

        String authHeader = request.getHeader(casProperties.getJwtTokenHead());

        String url = request.getRequestURI();

        if(!casProperties.getIgnoredUrl()[0].endsWith(url) && StringUtils.isBlank(authHeader)){
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            response.getWriter().println(JSONUtil.parse(Response.builderFailed().setCode("401").setMessage("暂未登录或token已经过期")));
            response.getWriter().flush();
            return;
        }

        if (authHeader != null && authHeader.startsWith(casProperties.getJwtTokenPrefix())) {

            // The part after "Bearer "
            String authToken = authHeader.substring(casProperties.getJwtTokenPrefix().length()).trim();

            Long userId = jwtTokenUtil.getUserIdFromToken(authToken);

            log.info("checking userId:{}", userId);

            if (userId != null && SecurityContextHolder.getContext().getAuthentication() == null) {

                UserDetailPlus userDetails = userDetailsPlusService.loadUserByUserId(userId);
                //if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                log.info("authenticated userId : {}", userId);
                SecurityContextHolder.getContext().setAuthentication(authentication);
                //}
            }
        }
        chain.doFilter(request, response);
    }
}
